package com.baixun.service.impl;

import com.baixun.constant.MessageConstant;
import com.baixun.entity.PageResult;
import com.baixun.entity.QueryPageBean;
import com.baixun.entity.Result;
import com.baixun.mapper.RoleMapper;
import com.baixun.mapper.UserMapper;
import com.baixun.pojo.Role;
import com.baixun.pojo.User;
import com.baixun.service.RoleService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
@Transactional
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private UserMapper userMapper;
    /**
     * 添加角色
     * @param role
     */
    @Override
    public void addRole(Role role) {

        if(role != null){

            //先查询数据库中是否有这个角色
            QueryWrapper<Role> wrapper = new QueryWrapper<>();
            wrapper.eq("role_name",role.getRoleName());
            Role tempRole = roleMapper.selectOne(wrapper);
            if(tempRole != null){
                throw new RuntimeException(role.getRoleName()+"已经存在");
            }else{
                //设置了mysql主键自动增长，但因为删除字段的操作导致主键不连续的解决
                roleMapper.alter_auto_increment();
                roleMapper.insert(role);
            }

        }else{
            throw new RuntimeException("role为null");
        }

    }

    /**
     * 更新角色
     * @param role
     */
    @Override
    public void updateRoleById(Role role) {

        //先查询数据库有没有这个角色
        QueryWrapper<Role> wrapper = new QueryWrapper<>();
        wrapper.eq("role_name",role.getRoleName());
        Role tempRole = roleMapper.selectOne(wrapper);
        if(tempRole != null){
            throw new RuntimeException(role.getRoleName()+"已经存在");
        }
        //乐观锁，先查询版本
        tempRole = roleMapper.selectById(role.getId());
        role.setVersion(tempRole.getVersion());
        role.setRoleStatus(tempRole.getRoleStatus());
        roleMapper.updateById(role);
    }

    /**
     * 改变角色状态,当改变状态为1或0（停用）时，有用户则不能，没有才能删除
     * @param id
     * @param status
     */
    @Override
    public void updateRoleStatus(Integer id, Byte status) {

        if(status !=0 && status != 1 && status !=2 ){
            throw new RuntimeException("没有此状态");
        }

        //查询相关用户,有则不能删除
        if (status == 0 || status == 2){
            List<User> users = userMapper.findUserByRole_id(id);
            if(users != null && users.size() >0){
                throw new RuntimeException("有相关用户，不能删除或停用该角色");
            }
        }
        //乐观锁
        Role tempRole = roleMapper.selectById(id);
        Role role = new Role();
        role.setId(id);
        role.setRoleStatus(status);
        role.setVersion(tempRole.getVersion());
        roleMapper.updateRoleStatus(role);

    }

    /**
     * 永久删除角色通过id
     * @param id
     */
    @Override
    public void deleteById(Integer id) {

        List<User> users = userMapper.findUserByRole_id(id);
        if(users == null || users.size()==0){
            roleMapper.deleteById(id);
        }else{
            throw new RuntimeException("用户表中有和此相关联的用户,删除失败");
        }
    }

    /**
     * 通过id查询角色
     * @param id
     */
    @Override
    public Role selectById(Integer id) {

        //仅查询status=1的，如果不是则抛出异常
        QueryWrapper<Role> wrapper = new QueryWrapper<>();
        wrapper.eq("role_status",1).eq("id",id);
        Role role = roleMapper.selectOne(wrapper);
        if(role == null){
            throw new RuntimeException("查询失败,没有此条数据");
        }
        return role;
    }

    /**
     * 通过条件分页查询角色
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult selectByConditionPage(QueryPageBean<String> queryPageBean) {

        //去掉roleName前后空格
        String roleName = queryPageBean.getQuery();
        if(roleName != null){
             roleName = roleName.trim();
        }
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        Page<Role> page = roleMapper.selectByCondition(roleName);
        return new PageResult(page.getTotal(),page.getResult());
    }
}
